const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event) => {
	try {
		const { oldBelongSpaceid, newBelongSpaceid, articleid } = event

		const DB = cloud.database()

		const article = await DB.collection('gn_article').doc(articleid).get()
		// 添加新的记录
		let space = await DB.collection('gn_space').doc(newBelongSpaceid).get()
		space.data.article.push({
			_id: article.data._id,
			title: article.data.title,
		})
		await DB.collection('gn_space')
			.doc(newBelongSpaceid)
			.update({
				data: {
					article: space.data.article,
				},
			})
		// 删除旧的记录
		space = await DB.collection('gn_space').doc(oldBelongSpaceid).get()
		const index = space.data.article.findIndex((art) => art._id === articleid)
		space.data.article.splice(index, 1)
		await DB.collection('gn_space')
			.doc(oldBelongSpaceid)
			.update({
				data: {
					article: space.data.article,
				},
			})
		//移动
		await DB.collection('gn_article')
			.doc(articleid)
			.update({
				data: {
					belong_space: newBelongSpaceid,
				},
			})

		space = await DB.collection('gn_space').doc(oldBelongSpaceid).get()

		return {
			data: {
				space: space.data,
			},
			code: 0,
			msg: '删除成功',
		}
	} catch (err) {
		throw err
	}
}
